package com.example.user

import android.content.Intent
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.network.CheckResultListenerAddresponse
import com.example.network.ResponseRegisterBean
import com.example.network.SendRequest
import java.util.regex.Pattern

class RegisterPassword : AppCompatActivity(), View.OnClickListener {
    private lateinit var backButton: ImageView
    private var username: String? = null
    private var vercode: String? = null
    private lateinit var btnSubmit: Button
    private lateinit var editText: EditText
    private lateinit var editTextAgain: EditText
    private lateinit var btnTogglePassword: ImageButton
    private lateinit var checkBoxAgreement: CheckBox
    private var isPasswordVisible = false
    
    companion object {
        // 密码筛选正则表达式
        private val PWD_PATTERN = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#@!%&*_,.?])[A-Za-z0-9#@!%&*_,.?]{9,}$")
        
        // 密码筛选
        fun isValidPassword(pwd: String?): Boolean {
            return pwd != null && PWD_PATTERN.matcher(pwd).matches()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.register_password_activity)
        username = intent.getStringExtra("userName")
        vercode = intent.getStringExtra("verCode")
        
        //绑定返回按钮并注册监听器
        backButton = findViewById(R.id.title_bar_back)
        backButton.setOnClickListener(this)

        //绑定提交按钮并注册监听器
        btnSubmit = findViewById(R.id.btn_submit)
        btnSubmit.isEnabled = false // 默认禁用注册按钮
        btnSubmit.setOnClickListener(this)

        // 初始化用户协议复选框
        checkBoxAgreement = findViewById(R.id.check_box_agreement)
        checkBoxAgreement.setOnCheckedChangeListener { _, isChecked ->
            // 根据复选框状态启用/禁用注册按钮
            btnSubmit.isEnabled = isChecked
        }

        //给两个密码输入框进行注册
        editText = findViewById(R.id.setPassWord)
        editTextAgain = findViewById(R.id.setPassWordAgain)
        
        // 初始化密码显示/隐藏按钮
        btnTogglePassword = findViewById(R.id.btn_toggle_password)
        btnTogglePassword.setOnClickListener(this)
        
        // 设置密码输入框默认隐藏密码
        editText.transformationMethod = PasswordTransformationMethod.getInstance()
        editTextAgain.transformationMethod = PasswordTransformationMethod.getInstance()
    }

    //注册用户
    private fun registerUser(username: String?, vercode: String?) {
        SendRequest.registerUser(username!!, vercode!!, object : CheckResultListenerAddresponse {
            override fun onSuccess(desc: ResponseRegisterBean) {
                // 注册成功时的处理
                val result = desc.getResultDesc()
                if (result == "成功") {
                    Toast.makeText(this@RegisterPassword, "注册成功", Toast.LENGTH_SHORT).show()
                    // 跳转到登录页面
                    val intent = Intent(this@RegisterPassword, LoginActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                    startActivity(intent)
                } else {
                    Toast.makeText(this@RegisterPassword, result, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFail(msg: String) {
                //网络报错处理
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.title_bar_back -> {
                finish()
            }
            R.id.btn_toggle_password -> {
                togglePasswordVisibility()
            }
            R.id.btn_submit -> {
                //首先进行密码格式筛选
                val editTextString = editText.text.toString().trim()
                val editTextStringAgain = editTextAgain.text.toString().trim()

                when {
                    // 存在输入框为空的情况
                    editTextString.isEmpty() || editTextStringAgain.isEmpty() -> {
                        Toast.makeText(this, "存在输入框为空", Toast.LENGTH_SHORT).show()
                    }
                    // 两次输入密码的内容不一致
                    editTextString != editTextStringAgain -> {
                        Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show()
                    }
                    // 密码格式不正确
                    !isValidPassword(editTextString) -> {
                        Toast.makeText(this, "密码格式不正确", Toast.LENGTH_SHORT).show()
                    }
                    //密码正确开始发送请求
                    else -> {
                        registerUser(username, vercode)
                    }
                }
            }
        }
    }
    
    /**
     * 统一切换两个密码输入框的显示和隐藏状态
     */
    private fun togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            editText.transformationMethod = PasswordTransformationMethod.getInstance()
            editTextAgain.transformationMethod = PasswordTransformationMethod.getInstance()
            btnTogglePassword.setImageResource(R.drawable.ic_password_eye_off)
        } else {
            // 显示密码
            editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
            editTextAgain.transformationMethod = HideReturnsTransformationMethod.getInstance()
            btnTogglePassword.setImageResource(R.drawable.ic_password_eye_on)
        }
        
        // 切换状态标志
        isPasswordVisible = !isPasswordVisible
        
        // 将光标移到文本末尾
        editText.setSelection(editText.text.length)
        editTextAgain.setSelection(editTextAgain.text.length)
    }
}